<template>
  <div ref="chart" class="chart-render-box"></div>
</template>
<script setup>
import * as echarts from 'echarts'
import { onMounted, ref, watch } from 'vue'
const props = defineProps({
  pieData: {
    type: Array,
    default: () => [],
  },
})
const option = ref({
  grid: {
    left: '0%',
    right: '0%',
    bottom: '0%',
    top: '10%',
    containLabel: true,
  },
  tooltip: {
    trigger: 'item',
    axisPointer: {
      type: 'shadow',
    },
    backgroundColor: 'rgba(24, 125, 255, 0.8)',
    textStyle: {
      color: '#ffffff',
    },
  },
  legend: {
    show: true,
    icon: 'circle',
    x: 'center',
    y: '90%',
    // data: ['一月', '二月', '三月'],
    textStyle: {
      color: '#fff',
    },
    type: 'scroll',
    pageIconColor: '#fff', // 翻页按钮的颜色
    pageIconInactiveColor: '#2f4554', // 翻页按钮不激活时（即翻页到头时）的颜色
  },
  series: [
    {
      type: 'pie',
      center: ['50%', '40%'],
      radius: ['60%', '45%'],
      clockwise: true,
      avoidLabelOverlap: true,
      hoverOffset: 15,
      itemStyle: {
        // normal: {
        //     color: function(params) {
        //         let colorList = ['#00FFFF','#037AFF','#73DDFF', '#73ACFF', '#FDD56A', '#FDB36A', '#FD866A', '#9E87FF', '#58D5FF']
        //         return colorList[params.dataIndex]
        //     },
        // },
      },
      label: {
        // show: true,
        // position: 'outside',
        // formatter: '{d}',
        // color: '#fff',
        // position: 'inside',
        formatter(item) {
          // console.log('@item', item)
          if (item.name === '') {
            return ''
          }
          //   return `${item.value}%`
          return item.name + '(' + item.value + ')'
        },
        textStyle: {
          fontSize: 12,
          color: '#ffffff',
        },
      },
      labelLine: {
        normal: {
          length: 40,
          length2: 30,
          lineStyle: {
            width: 1,
          },
        },
      },
      data: props.pieData,
    },
  ],
})
const chart = ref()
const initCharts = () => {
  chart.value.removeAttribute('_echarts_instance_')
  const myChart = echarts.init(chart.value)
  myChart.setOption(option.value)
}
watch(
  () => props.pieData,
  (newValue, oldValue) => {
    option.value.series[0].data = newValue
    initCharts()
  },
  { deep: true }
)
onMounted(() => {
  initCharts()
})
defineExpose({
  initCharts,
  props,
})
</script>
<style scoped lang="scss">
.chart-render-box {
  width: 100%;
  height: 100%;
  flex: 1;
}
</style>
